package com.leinao.dataset.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.leinao.category.dao.CategoryMapper;
import com.leinao.category.dto.CategoryRelationDto;
import com.leinao.commons.Response;
import com.leinao.commons.ResponseMessage;
import com.leinao.config.EnvironmentConfig;
import com.leinao.constant.*;
import com.leinao.dataset.dao.PaiDataSetMapper;
import com.leinao.dataset.dto.*;
import com.leinao.dataset.model.PaiDataSet;
import com.leinao.dataset.model.PaiObjectFileRelation;
import com.leinao.dataset.model.PaiUserDatasetRelation;
import com.leinao.dataset.service.DataSetService;
import com.leinao.util.page.PageInfo;
import com.leinao.util.random.RandomPrimaryCode;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author  wangshoufa 
 * @date 2018年11月7日 下午4:54:21
 *
 */
@Service
public class DataSetServiceImpl implements DataSetService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private PaiDataSetMapper dataSetMapper;

	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private EnvironmentConfig env;

	@Autowired
	private RestTemplate restTemplate;

	/**
	  * @Description 获取数据集
	  * @param userId	用户Id
	  * @param cp	当前页
	  * @param ps	每页展示条数
	  * @return 返回数据集列表
	  * @author:    weiwei
	  * @Date:  2019/4/22 13:54
	  */
	@Override
	public Response<PageInfo> getDataSetInfo(String userId, Integer cp, Integer ps) {
		PageInfo pageInfo=null;
		PageHelper.startPage(cp, ps);
		List<PaiDataSetDto> list = Lists.newArrayList();
		try {
			list = dataSetMapper.getDataSetInfo(userId);

			// 初始化数据集封面
			initDataSetCover(list);

			pageInfo = new PageInfo(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(),DataSetEnum.GET_DATASET_ERROR.getDesc(),null);
		}
		return Response.ok(pageInfo);
	}

	/**
	 * 
	 * 上传数据集信息（附示例照片）
	 * @param dataSet 数据集填写的信息
	 * @param ids 示例照片ID,多张以,分割
	 * @return
	 * @author wangshoufa
	 * @date 2018年11月20日 下午2:01:58
	 */
	@Transactional(rollbackFor=Exception.class)
	@Override
	public Response<Long> pushDataSet(HttpServletRequest request, PaiDataSetDto dataSet, String ids) {
		try {
			long currentTimeMillis = System.currentTimeMillis();
			String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
			LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
			if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
				return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
			}

			// 判断数据集的名称是否已存在
			PaiDataSet paiDataSet = dataSetMapper.getDataSetByName(dataSet.getName(), userInfo.getUserId());
			if(paiDataSet != null) {
				return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.DATASET_NAME_REPEAT.getSeq(), DatasetErrorEnum.DATASET_NAME_REPEAT.getDesc(), null);
			}

			String dataSetCode = RandomPrimaryCode.getPrimaryCode(Constant.PRIMARY_CODE_LENGTH);
			dataSet.setNumber(dataSetCode);
			dataSet.setUserId(userInfo.getUserId());
			dataSet.setProvider(userInfo.getEmail());
			String dataSetPath = env.getDatasetPath() + userInfo.getUserId() + File.separator + dataSet.getName();
			dataSet.setPath(dataSetPath);
			String dataSetContainePath = Constant.JOB_CONTAINER_PATH + dataSet.getName();
			dataSet.setContainerPath(dataSetContainePath);
			dataSet.setCreateTime(currentTimeMillis);
			dataSet.setUpdateTime(currentTimeMillis);
			int num = dataSetMapper.pushDataSet(dataSet);
			logger.info(String.format("insert into num: {}, return primaryKey id: {}", num, dataSet.getId()));
			if (StringUtils.isNotBlank(ids)) {
				// insert pai_object_file_relation
				String[] id = ids.split(",");
				List<PaiObjectFileRelation> list = Lists.newLinkedList();
				for (String file_id : id) {
					PaiObjectFileRelation pofr = new PaiObjectFileRelation();
					pofr.setFileId(Long.parseLong(file_id));
					pofr.setType(DataSetEnum.DATASET_FILE.getSeq());
					pofr.setObjId(dataSet.getId());
					pofr.setCreateTime(System.currentTimeMillis());
					pofr.setUpdateTime(System.currentTimeMillis());
					list.add(pofr);
				}
				dataSetMapper.batchInsertObjFileRelation(list);
			}
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.PUSH_DATASET_SUCCESS.getSeq(),
					DataSetEnum.PUSH_DATASET_SUCCESS.getDesc(), dataSet.getId());
		} 
		catch (MySQLIntegrityConstraintViolationException e) {
			logger.error(String.format("pushDataSet error by userId: %s", dataSet.getUserId()));
			logger.error(e.getMessage(), e);
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.PUSH_DATASET_NAME__ERROR.getSeq(), DataSetEnum.PUSH_DATASET_NAME__ERROR.getDesc(), null);
		}
		catch (Exception e) {
			logger.error("pushDataSet error");
			logger.error(e.getMessage(), e);
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.PUSH_DATASET_ERROR.getSeq(), DataSetEnum.PUSH_DATASET_ERROR.getDesc(), null);
		}
	}

	/**
	 * @Description 公开数据集
	 * @param userId : 用户ID
	 * @param publicDataSetDto : 公开用户信息
	 * @author lizi
	 * @date 2018/12/17 下午2:17
	 */
    @Transactional(value ="transactionManager", propagation = Propagation.REQUIRED)
	@Override
	public Response<Void> openDataSet(String userId, PublicDataSetDto publicDataSetDto) {
		Long datasetId = publicDataSetDto.getDatasetId();
		if(datasetId == null || datasetId.equals(Constant.DATASET_LONG_TYPE_EMPTY)) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.INVALID_DATASET_ID.getSeq(), DatasetErrorEnum.INVALID_DATASET_ID.getDesc());
		}

		// 数据集是否存在,以及拥有着判断
		PaiDataSet dataSet = dataSetMapper.selectByPrimaryKey(datasetId);
		if(dataSet == null) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.INVALID_DATASET_ID.getSeq(), DatasetErrorEnum.INVALID_DATASET_ID.getDesc());
		}
		if(!dataSet.getUserId().equals(userId)) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.DATASET_NO_AUTHORITY.getSeq(), DatasetErrorEnum.DATASET_NO_AUTHORITY.getDesc(), null);
		}
		// 公开数据集开关设置，公开所有人之后不能再关闭公开
		if(DatasetTypeEnum.PUBLIC.getType().equals(dataSet.getType()) && !publicDataSetDto.isOpenAllPerson()) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.DATASET_CAN_NOT_CLOSE.getSeq(), DatasetErrorEnum.DATASET_CAN_NOT_CLOSE.getDesc());
		}

		// 公开数据集
		if(publicDataSetDto.isOpenAllPerson() && !DatasetTypeEnum.PUBLIC.getType().equals(dataSet.getType())) {
			PaiDataSet updateDataSet = new PaiDataSet();
			updateDataSet.setId(datasetId);
			updateDataSet.setType(DatasetTypeEnum.PUBLIC.getType());
            updateDataSet.setIsPass(DatasetIsPassEnum.PASS.getStatus());
			dataSetMapper.updateByPrimaryKeySelective(updateDataSet);
		}

		List<String> friendUserIds = publicDataSetDto.getFriendUserIdList();
		for (int i = 0; i < friendUserIds.size(); i++) {
			if(friendUserIds.get(i).equals(userId)){
				return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
								DatasetErrorEnum.OPEN_PERSON_IS_DATASET_OWNER.getSeq(), DatasetErrorEnum.OPEN_PERSON_IS_DATASET_OWNER.getDesc());
			}
		}

		// 数据集公开人员列表
		List<String> dbUserIdList = dataSetMapper.selectUserIdListByDatasetId(datasetId);
		dbUserIdList = dbUserIdList == null ? new ArrayList<>() : dbUserIdList;

		// 所有需要公开的用户列表
		Set<String> userIdSet = new LinkedHashSet<>();
		if(!CollectionUtils.isEmpty(publicDataSetDto.getEnterpriseUserIdList())) {
			userIdSet.addAll(publicDataSetDto.getEnterpriseUserIdList());
		}
		if(!CollectionUtils.isEmpty(publicDataSetDto.getFriendUserIdList())) {
			userIdSet.addAll(publicDataSetDto.getFriendUserIdList());
		}

		// 需要删除的用户列表
		List<String> deleteUserIdList = new ArrayList<>(dbUserIdList);
		deleteUserIdList.removeAll(userIdSet);
		if(!CollectionUtils.isEmpty(deleteUserIdList)) {
			dataSetMapper.deleteUserDatasetRelation(datasetId, deleteUserIdList);

			// 如果数据集为非公开，则删除用户所有项目上使用的该数据集的关系
			if(!publicDataSetDto.isOpenAllPerson()) {
				dataSetMapper.deleteProjectDatasetRelation(datasetId, deleteUserIdList);
			}
		}

		// 需要新增的用户列表
		List<String> insertUserIdList = new ArrayList<>(userIdSet);
		insertUserIdList.removeAll(dbUserIdList);
		if(!CollectionUtils.isEmpty(insertUserIdList)) {
			List<PaiUserDatasetRelation> userDatasetRelationList = new ArrayList<>();
			long now = System.currentTimeMillis();
			insertUserIdList.forEach(insetUserId -> {
				PaiUserDatasetRelation userDatasetRelation = new PaiUserDatasetRelation();
				userDatasetRelation.setDatasetId(datasetId);
				userDatasetRelation.setUserId(insetUserId);
				userDatasetRelation.setCreateTime(now);
				userDatasetRelation.setUpdateTime(now);
				userDatasetRelationList.add(userDatasetRelation);
			});
			dataSetMapper.batchInsertUserDatasetRelation(userDatasetRelationList);
		}

		return Response.ok();
	}

	/**
	 * @Description 获取公开数据集列表
	 * @param categoryId : 分类ID
	 * @param userId : 用户ID
	 * @param pageNumber : 当前页
	 * @param pageSize : 每页条数
	 * @author lizi
	 * @date 2018/12/17 下午2:17
	 */
	@Override
	public Response<PageInfo> getPublicDataSetList(Long categoryId, String userId, Integer pageNumber, Integer pageSize) {
		PageHelper.startPage(pageNumber, pageSize);
		try {
			List<PaiDataSetDto> dataSetList = dataSetMapper.getPublicDataSetList(categoryId, userId);

			// 获取数据集使用次数（多少个项目使用了数据集）
            if(!CollectionUtils.isEmpty(dataSetList)) {
                // 获取数据集ID集合
                List<Long> dataSetIdList = dataSetList.stream().map(PaiDataSetDto::getId).collect(Collectors.toList());

                // 获取公开数据集项目使用次数
                List<PaiDataSetDto> dataSetProjectCountList = dataSetMapper.getPublicDataSetProjectCountList(dataSetIdList, userId);
                if(!CollectionUtils.isEmpty(dataSetProjectCountList)) {
                    dataSetList.forEach(dataSet -> {
                        dataSetProjectCountList.forEach(dataSetProjectCount -> {
                            if(dataSet.getId().equals(dataSetProjectCount.getId())) {
                                dataSet.setUserProjectCount(dataSetProjectCount.getUserProjectCount());
                            }
                        });
                    });
                }
            }

			// 初始化数据集封面
			initDataSetCover(dataSetList);

			// 初始化公开数据集人员信息
			initPublicDatasetUserInfo(dataSetList);

			// 初始化公开项目分类信息
			initDatasetCategoryInfo(dataSetList, categoryId == null ? Constant.DATASET_LONG_TYPE_EMPTY : categoryId);

			return Response.ok(new PageInfo<>(dataSetList));
		} catch (Exception e) {
			logger.error("getPublicDataSetList Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.GET_DATASET_LIST_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_LIST_ERROR.getDesc(),null);
		}
	}

	/**
	 * 项目创建时选择的数据集列表,包括公开数据集、个人私有数据集、被分享的数据集
	 * @param search : 搜索关键词
	 * @return
	 * @author wangshoufa
	 * @date 2018年11月28日
	 *
	 */
	@Override
	public Response<List<PaiDataSetDto>> optionalDataSet(String search, LoginResultDto userInfo) {
		List<PaiDataSetDto> list = Lists.newArrayList();
		try {
			list = dataSetMapper.optionalDataSet(search, userInfo.getUserId());

			// 因为sql中加入了排序规则，所以仍然需要对UNION的结果进行去重
			if(!CollectionUtils.isEmpty(list)) {
				Map<Long, PaiDataSetDto> distinctMap = new LinkedHashMap<>();
				list.forEach(dataSet -> distinctMap.put(dataSet.getId(), dataSet));
				list = new ArrayList<>(distinctMap.values());
			}

			// 初始化数据集封面
			initDataSetCover(list);
		} catch (Exception e) {
			logger.error(String.format("get dataSetList error userId is: {}", userInfo.getUserId()));
			logger.error(e.getMessage(), e);
		}
		return Response.ok(list);
	}

	/**
	 * 获取数据集明细
	 * @param userId	用户Id
	 * @param number	当前数据集的编号
	 * @return
	 * @author wangshoufa 
	 * @date 2018年11月28日
	 *
	 */
	@Override
	public Response<PaiDataSetDto> dataSetDetail(String userId, String number) {
		try {
			PaiDataSetDto result = dataSetMapper.dataSetDetail(userId, number);
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_DETAIL_SECCESS.getSeq(), DataSetEnum.GET_DATASET_DETAIL_SECCESS.getDesc(), result);
		} catch (Exception e) {
			logger.error(String.format("dataSetDetail error userId,: {}, number: {}", userId, number));
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_DETAIL_ERROR.getSeq(), DataSetEnum.GET_DATASET_DETAIL_ERROR.getDesc(), null);
		}
	}

	/**
	 * @Description 获取数据集共享人员信息
	 * @param datasetId : 数据集ID
	 * @param userInfo : 登录用户信息
	 * @author lizi
	 * @date 2018/12/17 下午2:19
	 */
	@Override
	public Response<DataSetSharingUserDto> getDataSetSharingUser(Long datasetId, LoginResultDto userInfo) {
		// 数据集是否存在,以及拥有着判断
		PaiDataSet dataSet = dataSetMapper.selectByPrimaryKey(datasetId);
		if(dataSet == null) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.INVALID_DATASET_ID.getSeq(), DatasetErrorEnum.INVALID_DATASET_ID.getDesc(), null);
		}
		if(!dataSet.getUserId().equals(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.DATASET_NO_AUTHORITY.getSeq(), DatasetErrorEnum.DATASET_NO_AUTHORITY.getDesc(), null);
		}

		// 定义数据集共享信息
		DataSetSharingUserDto dataSetSharingUser = new DataSetSharingUserDto();
		if(DatasetTypeEnum.PUBLIC.getType().equals(dataSet.getType())) {
			dataSetSharingUser.setOpenAllPerson(true);
		}

		// 获取数据集共享人员信息
		List<String> userIdList = dataSetMapper.selectUserIdListByDatasetId(datasetId);
		if(!CollectionUtils.isEmpty(userIdList)) {
			// 根据用户ID或邮箱获取用户信息
			Response<List<UserInfoDto>> response = requestUserInfo(userIdList);
			ResponseMessage responseMessage = response.getMessage();
			if(responseMessage.getCode() == ResponseMessage.SUCCESS_CODE) {
				dataSetSharingUser.setFriendUserList(response.getData());
			} else {
				return Response.error(Constant.RESPONSE_STATUS_SUCCESS, responseMessage.getCode(), responseMessage.getMessage(), null);
			}
		}

		return Response.ok(dataSetSharingUser);
	}

	/**
	 * @Description 根据邮箱查询用户信息
	 * @param email : 用户邮箱
	 * @param userInfo : 登录用户信息
	 * @author lizi
	 * @date 2018/12/17 下午2:19
	 */
	@Override
	public Response<UserInfoDto> getSharingUserInfo(String email, LoginResultDto userInfo) {
		// 获取数据集共享人员信息
		List<String> emailList = new ArrayList<>();
		emailList.add(email);
		// 根据用户ID或邮箱获取用户信息
		Response<List<UserInfoDto>> response = requestUserInfo(emailList);
		ResponseMessage responseMessage = response.getMessage();
		if(responseMessage.getCode() == ResponseMessage.SUCCESS_CODE && response.getData().size() > 0) {
			return Response.ok(response.getData().get(0));
		} else {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, responseMessage.getCode(), responseMessage.getMessage(), null);
		}
	}

	/**
	 * @Description 根据用户ID或邮箱获取用户信息
	 * @param userIdOrEmailList : 用户ID或邮箱列表
	 * @author lizi
	 * @date 2018/12/6 上午11:49
	 */
	@SuppressWarnings("unchecked")
	private Response<List<UserInfoDto>> requestUserInfo(List<String> userIdOrEmailList) {
		try {
			// 复制项目代码
			StringBuilder urlBuilder = new StringBuilder(env.getBitahubServiceUrl()).append(Constant.BITAHUB_USER_INFO_GET_API).append("?");
			for(String userIdOrEmail : userIdOrEmailList) {
				urlBuilder.append("userIdOrEmailList=").append(userIdOrEmail).append("&");
			}
			urlBuilder.delete(urlBuilder.length() - 1, urlBuilder.length());
			logger.info("requestUserInfo url: {}", urlBuilder);
			ResponseEntity<Map> response = restTemplate.getForEntity(urlBuilder.toString(), Map.class);
			// 请求失败
			if(response.getStatusCode() != HttpStatus.OK) {
				logger.info("request user info failure, userIdList: {}, StatusCode : {}", userIdOrEmailList, response.getStatusCode());
				return Response.error(200, DatasetErrorEnum.USER_INFO_GET_FAILURE.getSeq(), DatasetErrorEnum.USER_INFO_GET_FAILURE.getDesc(), null);
			}
			Map responseMap = response.getBody();
			logger.info("request user info result, responseMap: {}, userIdOrEmailList: {}", responseMap, userIdOrEmailList);
			if(responseMap == null) {
				return Response.error(200, DatasetErrorEnum.USER_INFO_GET_FAILURE.getSeq(), DatasetErrorEnum.USER_INFO_GET_FAILURE.getDesc(), null);
			}

			// 解析请求结果
			Integer code = (Integer)responseMap.get("code");
			if(code == ResponseMessage.SUCCESS_CODE) {
				List<UserInfoDto> userInfoList = new ArrayList<>();
				List<Map> resultMap = (List<Map>)responseMap.get("result");
				if(!CollectionUtils.isEmpty(resultMap)) {
					resultMap.forEach(result -> {
						UserInfoDto userInfoDto = new UserInfoDto();
						userInfoDto.setUserId((String)result.get("userId"));
						userInfoDto.setUsername((String)result.get("username"));
						userInfoDto.setHeadImage((String)result.get("headImage"));
						userInfoList.add(userInfoDto);
					});
					return Response.ok(userInfoList);
				}
			}
			return Response.error(200, DatasetErrorEnum.USER_INFO_GET_FAILURE.getSeq(), DatasetErrorEnum.USER_INFO_GET_FAILURE.getDesc(), null);
		} catch (Exception e) {
			logger.error("requestUserInfo Exception", e);
			return Response.error(200, DatasetErrorEnum.USER_INFO_GET_FAILURE.getSeq(), DatasetErrorEnum.USER_INFO_GET_FAILURE.getDesc(), null);
		}
	}

	/**
	  * @Description 获取公开数据集信息
	  * @param cp  当前页
	  * @param ps	每页展示条数
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/4/22 11:11
	  */
	@Override
	public Response<PageInfo> queryOpenDataSetInfo(Integer cp, Integer ps) {
		PageInfo pageInfo=null;
		PageHelper.startPage(cp, ps);
		List<PaiDataSetDto> list = Lists.newArrayList();
		try {
			list = dataSetMapper.queryOpenDataSetInfo();

			// 初始化数据集封面
			initDataSetCover(list);

			pageInfo = new PageInfo(list);
			return Response.ok(pageInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return Response.ok(pageInfo);
	}

	/**
	 * 获取项目数据集列表
	 * @param projectId : 项目ID
	 * @param userId : 用户ID
	 * @return
	 */
	@Override
	public Response<List<PaiDataSetDto>> getProjectDataSetList(Long projectId, String userId) {
		List<PaiDataSetDto> list = dataSetMapper.getProjectDataSetList(projectId, userId);
		return Response.ok(list == null ? Collections.emptyList() : list);
	}

	/**
	 * @Description 搜索公开数据集列表信息
	 * @param search : 搜索内容
	 * @param userId : 用户ID
	 * @param pageNumber : 当前页
	 * @param pageSize : 每页条数
	 * @author lizi
	 * @date 2019/02/26 下午5:17
	 */
	@Override
	public Response<PageInfo> searchPublicDataSetList(String search, String userId, Integer pageNumber, Integer pageSize) {
		PageHelper.startPage(pageNumber, pageSize);
		try {
			List<PaiDataSetDto> dataSetList = dataSetMapper.searchPublicDataSetList(search, userId);

			// 初始化数据集封面
			initDataSetCover(dataSetList);

            return Response.ok(new PageInfo<>(dataSetList));
		} catch (Exception e) {
			logger.error("searchPublicDataSetList Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.GET_DATASET_LIST_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_LIST_ERROR.getDesc(),null);
		}
	}

    /**
     * @Description 数据集是否公开给个人用户
     * @param dataSetId	数据集Id
     * @return
     * @author:    weiwei
     * @Date:  2019/5/17 14:11
     */
    @Override
    public Response<Boolean> checkDataSetPublicPersonFlag(Long dataSetId) {

        try{
            Integer count = dataSetMapper.checkDataSetPublicPersonFlag(dataSetId);
            if(count == 0){
                return Response.ok(false);
            }else {
                return Response.ok(true);
            }
        } catch (Exception e) {
            logger.error("checkDataSetPublicPersonFlag Exception", e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
                    DatasetErrorEnum.GET_USER_DATASET_ATTENTION_FALG_ERROR.getSeq(), DatasetErrorEnum.GET_USER_DATASET_ATTENTION_FALG_ERROR.getDesc(),null);
        }
    }

    /**
      * @Description    数据集公开给个人用户列表
      * @param datasetId    数据集Id
      * @param userInfo     用户信息
      * @return
      * @author:    weiwei
      * @Date:  2019/5/18 11:05
      */
    @Override
    public Response<DataSetSharingUserDto> getDataSetSharingUserList(Long datasetId, LoginResultDto userInfo) {

        try {
            PaiDataSet dataSet = dataSetMapper.selectByPrimaryKey(datasetId);
            if(null == dataSet) {
                return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
                        DatasetErrorEnum.DATASET_IS_NOT_EXIST_ERROR.getSeq(), DatasetErrorEnum.DATASET_IS_NOT_EXIST_ERROR.getDesc(), null);
            }
            if(!dataSet.getUserId().equals(userInfo.getUserId())) {
                return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
                        DatasetErrorEnum.DATASET_IS_NOT_USER_OWN.getSeq(), DatasetErrorEnum.DATASET_IS_NOT_USER_OWN.getDesc(), null);
            }

            //判断数据集是否为公开
            DataSetSharingUserDto dataSetSharingUser = new DataSetSharingUserDto();
            if(DatasetTypeEnum.PUBLIC.getType().equals(dataSet.getType())) {
                dataSetSharingUser.setOpenAllPerson(true);
            }

            // 获取数据集共享人员信息
            List<UserInfoDto> userList =  Lists.newArrayList();
            userList = dataSetMapper.getDataSetSharingUserList(datasetId);

            for (int i = 0; i < userList.size() ; i++) {
                userList.get(i).setHeadImage(Constant.QINIU_URL + userList.get(i).getHeadImage());
            }
            dataSetSharingUser.setFriendUserList(userList);
            return Response.ok(dataSetSharingUser);
        }catch (Exception e){
            logger.error("getDataSetSharingUserList Exception", e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
                    DatasetErrorEnum.GET_DATASET_SHARING_USER_LIST_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_SHARING_USER_LIST_ERROR.getDesc(),null);
        }
    }


	/**
	  * @Description 关注/取消关注数据集
	  * @param dataSetId	数据集Id
	  * @param attentionFlag	关注/取消关注标记  0:取消关注	1:关注
	  * @param userInfo		用户信息
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/15 14:35
	  */
	@Override
	public Response<Void> attentionDataSet(Long dataSetId, Integer attentionFlag, LoginResultDto userInfo) {
		try {
			PaiDataSetDto dataSet = dataSetMapper.getDataSetById(dataSetId);

			if (null == dataSet) {
				return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_IS_NOT_EXIST_ERROR.getSeq(),
						DataSetEnum.DATASET_IS_NOT_EXIST_ERROR.getDesc(), null);
			}

			if (null!= dataSet && userInfo.getUserId().equals(dataSet.getUserId())) {
				return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.USER_ATTENTION_OWN_DATASET_ERROR.getSeq(),
						DataSetEnum.USER_ATTENTION_OWN_DATASET_ERROR.getDesc(), null);
			}

			//查询该数据集是否公开给用户
			Integer publicCount = dataSetMapper.getUserDataSetPublicStatus(dataSetId, userInfo.getUserId());
			if(publicCount == 0 && dataSet.getType() == 0){
				return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_IS_NOT_PUBLIC.getSeq(),
						DataSetEnum.DATASET_IS_NOT_PUBLIC.getDesc(), null);
			}

			Integer count = dataSetMapper.getUserAttentionStatus(dataSetId, userInfo.getUserId());
			if (attentionFlag.equals(Constant.DATASET_NO_ATTENTION)) {
				//并未关注该数据集
				if (count == 0) {
					return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_NO_ATTENTION_BY_USER_ERROR.getSeq(),
							DataSetEnum.DATASET_NO_ATTENTION_BY_USER_ERROR.getDesc(), null);
				}

				Integer delCount = dataSetMapper.deleteUserAttention(dataSetId, userInfo.getUserId());
				if (delCount == Constant.UPDATE_COUNT) {
					return Response.ok();
				} else {
					return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ATTENTION_RELATION_DELETE_ERROR.getSeq(),
							DataSetEnum.DATASET_ATTENTION_RELATION_DELETE_ERROR.getDesc(), null);
				}
			} else {
				//已经关注该数据集
				if (count == 1) {
					return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_IS_ATTENTION_BY_USER_ERROR.getSeq(),
							DataSetEnum.DATASET_IS_ATTENTION_BY_USER_ERROR.getDesc(), null);
				}
				Integer insertCount = dataSetMapper.insertUserAttention(dataSetId, attentionFlag, userInfo.getUserId());
				if (insertCount == Constant.UPDATE_COUNT) {
					return Response.ok();
				} else {
					return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.DATASET_ATTENTION_RELATION_INSERT_ERROR.getSeq(),
							DataSetEnum.DATASET_ATTENTION_RELATION_INSERT_ERROR.getDesc(), null);
				}
			}

		} catch (Exception e) {
			logger.error("attentionDataSet Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.ATTENTION_DATASET_FAIL.getSeq(), DatasetErrorEnum.ATTENTION_DATASET_FAIL.getDesc(),null);
		}
	}
	
	/**
	  * @Description 	获取数据集
	  * @param userId	用户Id
	  * @param pageNumber	当前页数
	  * @param pageSize		每页展示条数
	  * @param dataSetType	数据集类型
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/15 17:05
	  */
	@Override
	public Response<PageInfo> getUserDataSet(String userId, Integer pageNumber, Integer pageSize, Integer dataSetType) {

		PageInfo pageInfo = null;
		PageHelper.startPage(pageNumber, pageSize);
		List<PaiDataSetDto> userDataSets = Lists.newArrayList();
		try {
			if(null != dataSetType && dataSetType == Constant.USER_ATTENTION_DATASET){
				userDataSets = dataSetMapper.getUserAttentionDataSet(userId);
			}else {
				userDataSets = dataSetMapper.getUserAllDataSet(userId);
			}
			// 初始化数据集封面
			initDataSetCover(userDataSets);
			pageInfo = new PageInfo(userDataSets);
		} catch (Exception e) {
			logger.error("getUserDataSet Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DataSetEnum.GET_DATASET_ERROR.getSeq(),DataSetEnum.GET_DATASET_ERROR.getDesc(),null);
		}
		return Response.ok(pageInfo);
	}
	
	/**
	  * @Description 公开数据集列表
	  * @param pageNumber
	  * @param pageSize
	  * @param categoryId
	  * @param userInfo
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/16 16:06
	  */
	@Override
	public Response<PageInfo> optionalDataSetExceptOwn(Integer pageNumber, Integer pageSize, Long categoryId, LoginResultDto userInfo) {

		PageInfo pageInfo = null;
		PageHelper.startPage(pageNumber, pageSize);
		List<PaiDataSetDto> dataSetList = Lists.newArrayList();
		try {
			dataSetList = dataSetMapper.optionalDataSetExceptOwn(categoryId, userInfo.getUserId());

			// 初始化数据集封面
			initDataSetCover(dataSetList);

			// 初始化公开数据集人员信息
			initPublicDatasetUserInfo(dataSetList);

			// 初始化公开项目分类信息
			initDatasetCategoryInfo(dataSetList, categoryId == null ? Constant.DATASET_LONG_TYPE_EMPTY : categoryId);

			pageInfo = new PageInfo(dataSetList);

		} catch (Exception e) {
			logger.error("optionalDataSetExceptOwn Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.GET_DATASET_LIST_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_LIST_ERROR.getDesc(),null);
		}
		return Response.ok(pageInfo);
	}

	/**
	  * @Description 获取用户是否关注数据集
	  * @param dataSetId	数据集Id
	  * @param userInfo		用户信息
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/16 13:54
	  */
	@Override
	public Response<DataSetAttentionInfo> getUserAttentionStatus(Long dataSetId, LoginResultDto userInfo) {

		try {
			Integer count = dataSetMapper.getUserAttentionStatus(dataSetId, userInfo.getUserId());
			Integer attentionCount = dataSetMapper.getDataSetAttentionCount(dataSetId);
			String username = dataSetMapper.getUsername(dataSetId);
			DataSetAttentionInfo dataSetAttentionInfo = new DataSetAttentionInfo();
			dataSetAttentionInfo.setUsername(username);
			dataSetAttentionInfo.setAttentionCount(attentionCount);
			if(count == 1){
				dataSetAttentionInfo.setAttentionFlag(true);
			}else {
				dataSetAttentionInfo.setAttentionFlag(false);
			}
			return Response.ok(dataSetAttentionInfo);
		} catch (Exception e) {
			logger.error("getUserAttentionStatus Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
					DatasetErrorEnum.GET_USER_ATTENTION_DATASET_FALG_ERROR.getSeq(), DatasetErrorEnum.GET_USER_ATTENTION_DATASET_FALG_ERROR.getDesc(),null);
		}
	}


	/**
	  * @Description 公开数据集列表,不包含其本人公开的和关注的
	  * @param pageNumber	当前页数
	  * @param pageSize		每页展示调试
	  * @param userInfo		用户信息
	  * @return
	  * @author:    weiwei
	  * @Date:  2019/5/17 15:12
	  */
	@Override
	public Response<PageInfo> optionalDataSetExceptOwnAndAttention(Integer pageNumber, Integer pageSize, LoginResultDto userInfo) {

		PageInfo pageInfo = null;
		PageHelper.startPage(pageNumber, pageSize);
		List<PaiDataSetDto> dataSetList = Lists.newArrayList();
		try {
			dataSetList = dataSetMapper.optionalDataSetExceptOwnAndAttention(userInfo.getUserId());

			// 初始化数据集封面
			initDataSetCover(dataSetList);

			// 初始化公开数据集人员信息
			initPublicDatasetUserInfo(dataSetList);

			pageInfo = new PageInfo(dataSetList);

		} catch (Exception e) {
			logger.error("optionalDataSetExceptOwnAndAttention Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, DatasetErrorEnum.GET_DATASET_LIST_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_LIST_ERROR.getDesc(),null);
		}
		return Response.ok(pageInfo);
	}

	@Override
	public Response<String> getDataSetProfile(Long dataSetId) {

		String dataSetProfile;
		try {
			dataSetProfile = dataSetMapper.getDataSetProfile(dataSetId);
		} catch (Exception e) {
			logger.error("getDataSetConfig Exception", e);
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS,
					DatasetErrorEnum.GET_DATASET_PROFILE_ERROR.getSeq(), DatasetErrorEnum.GET_DATASET_PROFILE_ERROR.getDesc(),null);
		}
		return Response.ok(dataSetProfile);
	}

	/**
	 * @Description 初始化数据集封面
	 * @param dataSet : 数据集
	 * @author lizi
	 * @date 2019/02/27 下午5:17
	 */
	private void initDataSetCover(PaiDataSetDto dataSet) {
		List<PaiDataSetDto> dataSetList = new ArrayList<>();
		dataSetList.add(dataSet);

		// 初始化数据集封面
		initDataSetCover(dataSetList);
	}

	/**
	 * @Description 初始化数据集封面
	 * @param dataSetList : 数据集集合
	 * @author lizi
	 * @date 2019/02/27 下午5:17
	 */
	private void initDataSetCover(List<PaiDataSetDto> dataSetList) {
		if(CollectionUtils.isEmpty(dataSetList)) {
			return;
		}

		// 获取数据集封面图片地址
		List<Long> dataSetIdList = dataSetList.stream().map(PaiDataSetDto::getId).collect(Collectors.toList());
		List<PaiDataSetDto> dataSetCoverUrlList = dataSetMapper.getDataSetCoverUrlList(dataSetIdList);
		if(!CollectionUtils.isEmpty(dataSetCoverUrlList)) {
			dataSetList.forEach(dataSet -> {
				dataSetCoverUrlList.forEach(dataSetCoverUrl -> {
					if(dataSet.getId().equals(dataSetCoverUrl.getId()) && StringUtils.isNotEmpty(dataSetCoverUrl.getCoverUrl())) {
						dataSet.setCoverUrl(dataSetCoverUrl.getCoverUrl());
						dataSet.setThumbnailUrl(dataSetCoverUrl.getCoverUrl() + Constant.DATASET_COVER_FORMAT);
					}
				});
			});
		}
	}

	/**
	 * @Description 初始化数据集分类信息
	 * @param dataSetList : 数据集列表信息
	 * @author lizi
	 * @date 2019/03/20 下午7:07
	 */
	private void initDatasetCategoryInfo(List<PaiDataSetDto> dataSetList, Long categoryId) {
		if(CollectionUtils.isEmpty(dataSetList)) {
			return;
		}

		// 获取数据集对应的项目ID集合
		List<Long> datasetIdList = dataSetList.stream().map(PaiDataSetDto::getId).collect(Collectors.toList());
		List<CategoryRelationDto> categoryRelationList = categoryMapper.getCategoryListByObjectIdListAndType(datasetIdList, CategoryRelationTypeEnum.DATASET.getType());
		if(CollectionUtils.isEmpty(categoryRelationList)) {
			return;
		}

		for(int i = 0; i < dataSetList.size(); i ++){
			for(int j = 0; j < categoryRelationList.size(); j ++){
				if(dataSetList.get(i).getId().equals(categoryRelationList.get(j).getObjId())) {
					if(categoryId.equals(categoryRelationList.get(j).getCategoryId())){
						CategoryRelationDto first = categoryRelationList.get(0);
						dataSetList.get(i).getCategoryList().add(0,categoryRelationList.get(j));
					}else {
						dataSetList.get(i).getCategoryList().add(categoryRelationList.get(j));
					}
				}
			}
		}
	}

	/**
	 * @Description 初始化公开数据集人员信息
	 * @param dataSetList : 数据集列表
	 * @author lizi
	 * @date 2019/03/21 下午2:07
	 */
	private void initPublicDatasetUserInfo(List<PaiDataSetDto> dataSetList) {
		if(CollectionUtils.isEmpty(dataSetList)) {
			return;
		}

		// 获取公开数据集对应的用户ID集合
		List<String> userIdList = dataSetList.stream().map(PaiDataSetDto::getUserId).collect(Collectors.toList());
		if(CollectionUtils.isEmpty(userIdList)) {
			return;
		}

		// 初始化用户信息
		Response<List<UserInfoDto>> response = requestUserInfo(userIdList);
		ResponseMessage responseMessage = response.getMessage();
		if(responseMessage.getCode() == ResponseMessage.SUCCESS_CODE) {
			List<UserInfoDto> userInfoList = response.getData();
			if(CollectionUtils.isEmpty(userInfoList)) {
				return;
			}
			userInfoList.forEach(user -> {
				dataSetList.forEach(dataset -> {
					if(user.getUserId().equals(dataset.getUserId())) {
						dataset.setUserName(user.getUsername());
						dataset.setHeadImage(user.getHeadImage());
					}
				});
			});
		}
	}
}
